class GeneralNewsLetter < ActiveRecord::Base
  has_and_belongs_to_many :countries
  has_many :news_offered_materials, :as => :news_reference
  has_many :general_news_letters_materials, :dependent => :destroy
  has_many :materials, :through => :general_news_letters_materials

  validates_presence_of :description, :subject_mail_spanish, :subject_mail_english
  validates_uniqueness_of :description

  #estados de la lista
  STATE_READY_TO_SEND  = "state_ready_to_send"
  STATE_ALREADY_SENT   = "state_already_sent"

  def self.search(search_description, search_state, page)
    items_per_page = count_record_per_page :general_news_letters
    order = "date_to_send desc, description"

    conditions_clauses = []
    conditions_options = []
    if !search_description.nil? && search_description.size != 0
      conditions_clauses << "upper(description) like upper(?)"
      conditions_options << "%#{search_description}%"
    end
    if !search_state.nil? && search_state != "state_all"
      conditions_clauses << "state = ?"
      conditions_options << "#{search_state}"
    end

    conditions = [conditions_clauses.join(" AND "), conditions_options].flatten

    @general_news_letters = GeneralNewsLetter.paginate :per_page => items_per_page,:page => page, :conditions => conditions, :order => order
    return @general_news_letters
  end

  def self.get_ready_to_send
    GeneralNewsLetter.find(:all, :conditions => ["state = ? and date_to_send <= ?",STATE_READY_TO_SEND, Time.now], :order => "date_to_send")
  end

end
